from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.models.department import Department
from app.models.employee import Employee
from app.schemas.department import DepartmentCreate, DepartmentUpdate, DepartmentInDB, DepartmentTree

router = APIRouter()

@router.post("", response_model=DepartmentInDB, summary="创建部门")
async def create_department(
    department: DepartmentCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建新部门"""
    # 检查父部门
    if department.parent_id:
        parent = db.query(Department).filter(Department.id == department.parent_id).first()
        if not parent:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="父部门不存在"
            )
    
    # 检查部门主管
    if department.manager_id:
        manager = db.query(Employee).filter(Employee.id == department.manager_id).first()
        if not manager:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门主管不存在"
            )
    
    db_department = Department(**department.model_dump())
    db.add(db_department)
    db.commit()
    db.refresh(db_department)
    return db_department

@router.get("", response_model=List[DepartmentInDB], summary="获取部门列表")
async def get_departments(
    skip: int = 0,
    limit: int = 10,
    name: Optional[str] = None,
    parent_id: Optional[int] = None,
    status: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取部门列表，支持分页和筛选"""
    query = db.query(Department)
    
    if name:
        query = query.filter(Department.name.like(f"%{name}%"))
    if parent_id is not None:
        query = query.filter(Department.parent_id == parent_id)
    if status is not None:
        query = query.filter(Department.status == status)
        
    departments = query.offset(skip).limit(limit).all()
    
    # 添加员工数量和主管名称信息
    for dept in departments:
        dept.employee_count = len(dept.employees)
        dept.manager_name = dept.manager.name if dept.manager else None
        dept.parent_name = dept.parent.name if dept.parent else None
    
    return departments

@router.get("/tree", response_model=List[DepartmentTree], summary="获取部门树形结构")
async def get_department_tree(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取部门的树形结构"""
    def build_tree(parent_id: Optional[int] = None) -> List[DepartmentTree]:
        departments = db.query(Department).filter(Department.parent_id == parent_id).all()
        tree = []
        for dept in departments:
            dept_dict = DepartmentTree(
                id=dept.id,
                name=dept.name,
                parent_id=dept.parent_id,
                manager_id=dept.manager_id,
                status=dept.status,
                description=dept.description,
                create_time=dept.create_time,
                update_time=dept.update_time,
                employee_count=len(dept.employees),
                manager_name=dept.manager.name if dept.manager else None,
                parent_name=dept.parent.name if dept.parent else None,
                children=build_tree(dept.id)
            )
            tree.append(dept_dict)
        return tree
    
    return build_tree(None)

@router.get("/{department_id}", response_model=DepartmentInDB, summary="获取部门详情")
async def get_department(
    department_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """根据ID获取部门详情"""
    department = db.query(Department).filter(Department.id == department_id).first()
    if not department:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="部门不存在"
        )
    
    # 添加员工数量和主管名称信息
    department.employee_count = len(department.employees)
    department.manager_name = department.manager.name if department.manager else None
    department.parent_name = department.parent.name if department.parent else None
    
    return department

@router.put("/{department_id}", response_model=DepartmentInDB, summary="更新部门信息")
async def update_department(
    department_id: int,
    department: DepartmentUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新部门信息"""
    db_department = db.query(Department).filter(Department.id == department_id).first()
    if not db_department:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="部门不存在"
        )
    
    # 检查父部门
    if department.parent_id:
        if department.parent_id == department_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="部门不能作为自己的父部门"
            )
        parent = db.query(Department).filter(Department.id == department.parent_id).first()
        if not parent:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="父部门不存在"
            )
    
    # 检查部门主管
    if department.manager_id:
        manager = db.query(Employee).filter(Employee.id == department.manager_id).first()
        if not manager:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门主管不存在"
            )
    
    for field, value in department.model_dump(exclude_unset=True).items():
        setattr(db_department, field, value)
    
    db.commit()
    db.refresh(db_department)
    
    # 添加员工数量和主管名称信息
    db_department.employee_count = len(db_department.employees)
    db_department.manager_name = db_department.manager.name if db_department.manager else None
    db_department.parent_name = db_department.parent.name if db_department.parent else None
    
    return db_department

@router.delete("/{department_id}", status_code=status.HTTP_204_NO_CONTENT, summary="删除部门")
async def delete_department(
    department_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除部门"""
    department = db.query(Department).filter(Department.id == department_id).first()
    if not department:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="部门不存在"
        )
    
    # 检查是否有子部门
    if db.query(Department).filter(Department.parent_id == department_id).first():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="请先删除子部门"
        )
    
    # 检查是否有员工
    if department.employees:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="请先转移或删除部门下的员工"
        )
    
    db.delete(department)
    db.commit() 